import { RigidBody } from "@react-three/rapier";
import { sharedBoxGeometry } from "../../../../common/geometry/geometry.js";
import {
  shadedGround2Material,
  shadedObstacleMaterial,
} from "../../../../common/material/material.js";
import { useRef } from "react";
import { useFrame } from "@react-three/fiber";
import * as THREE from "three";
import { useState } from "react";
/**
 *障碍物-自旋
 */
function BlockSpiner({ position = [0, 0, 0] }) {
  const [speed] = useState(
    () => (Math.random() + 0.2) * (Math.random() < 0.5 ? -1 : 1)
  );
  const obstacleRef = useRef();
  useFrame((state) => {
    // 设置障碍物旋转动画
    const time = state.clock.getElapsedTime();
    const elua = new THREE.Euler(0, time*speed, 0);
    const quaternion = new THREE.Quaternion();
    quaternion.setFromEuler(elua);
    if (obstacleRef.current) {
      obstacleRef.current.setNextKinematicRotation(quaternion);
    }
  });
  return (
    <>
      <group position={position}>
          <mesh
            position={[0, -0.1, 0]}
            scale={[4, 0.2, 4]}
            geometry={sharedBoxGeometry}
            material={shadedGround2Material}
            receiveShadow
          ></mesh>
        {/* 障碍物 */}
        <RigidBody
          ref={obstacleRef}
          type="kinematicPosition"
          //  设置弹性系数，确保球碰撞后的轻轻地弹
          restitution={0.2}
        >
          <mesh
            position={[0, 0.15, 0]}
            scale={[3.5, 0.3, 0.3]}
            geometry={sharedBoxGeometry}
            material={shadedObstacleMaterial}
            receiveShadow
            castShadow
          ></mesh>
        </RigidBody>
      </group>
    </>
  );
}
export default BlockSpiner;
